package com.tomato.controller;

import com.tomato.dto.Result;
import com.tomato.dto.TodoSettingDTO;
import com.tomato.dto.TodoSettingSyncDTO;
import com.tomato.entity.TodoSetting;
import com.tomato.service.TodoSettingService;
import com.tomato.util.JwtUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/task/template")
@Tag(name = "待办设定", description = "待办事项模板管理接口")
public class TodoSettingController {
    private final TodoSettingService todoSettingService;
    private final JwtUtil jwtUtil; // 注入JwtUtil

    public TodoSettingController(TodoSettingService todoSettingService, JwtUtil jwtUtil) {
        this.todoSettingService = todoSettingService;
        this.jwtUtil = jwtUtil;
    }

    @Operation(summary = "创建待办设定")
    @PostMapping
    public Result<TodoSetting> createSetting(
            @RequestHeader("Authorization") String token,
            @RequestBody TodoSettingDTO settingDTO) {
        Long userId = jwtUtil.getUserIdFromToken(token.replace("Bearer ", ""));
        log.debug("Create todo setting request for user: {}", userId);
        TodoSetting setting = todoSettingService.createSetting(userId, settingDTO);
        return Result.success(setting);
    }

    @Operation(summary = "获取用户所有待办设定")
    @GetMapping("/pull")
    public Result<List<TodoSetting>> getUserSettings(
            @RequestHeader("Authorization") String token) {
        Long userId = jwtUtil.getUserIdFromToken(token.replace("Bearer ", ""));
        log.debug("Get todo settings request for user: {}", userId);
        List<TodoSetting> settings = todoSettingService.getUserSettings(userId);
        return Result.success(settings);
    }

    @Operation(summary = "全量覆盖式同步待办设定")
    @PostMapping("/push")
    public Result<Void> syncSettings(
            @RequestHeader("Authorization") String token,
            @RequestBody List<TodoSettingSyncDTO> settings) {
        Long userId = jwtUtil.getUserIdFromToken(token.replace("Bearer ", ""));
        log.debug("Sync todo settings request for user: {} with {} settings", userId, settings.size());
        todoSettingService.syncSettings(userId, settings);
        return Result.success();
    }
}